/*
 * This file Copyright (c) 2015. Walle.
 * (http://www.wallellen.com). All rights reserved.
 *
 *
 * This file is dual-licensed under both the
 * Walle Agreement (WA) and the GNU General Public License.
 * You may elect to use one or the other of these licenses.
 *
 * This file is distributed in the hope that it will be
 * useful, but AS-IS and WITHOUT ANY WARRANTY; without even the
 * implied warranty of MERCHANTABILITY or FITNESS FOR A
 * PARTICULAR PURPOSE, TITLE, or NONINFRINGEMENT.
 * Redistribution, except as permitted by whichever of the GPL
 * or WA you select, is prohibited.
 *
 * 1. For the GPL license (GPL), you can redistribute and/or
 * modify this file under the terms of the GNU General
 * Public License, Version 3, as published by the Free Software
 * Foundation.  You should have received a copy of the GNU
 * General Public License, Version 3 along with this program;
 * if not, write to the Free Software Foundation, Inc., 51
 * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * 2. For the Walle Agreement (WA), this file
 * and the accompanying materials are made available under the
 * terms of the WA which accompanies this distribution, and
 * is available at http://www.wallellen.com/agreement.html
 *
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
 */

package com.wallellen.knowledge.doc.server.impl;

import com.wallellen.core.auth.domain.LoginUser;
import com.wallellen.core.sql.query.DBRule;
import com.wallellen.core.sql.query.DBSort;
import com.wallellen.core.sql.query.DataQuery;
import com.wallellen.core.sql.result.DataResult;
import com.wallellen.core.time.TimeTool;
import com.wallellen.knowledge.doc.dao.DocDaoInter;
import com.wallellen.knowledge.doc.dao.DocmessageDaoInter;
import com.wallellen.knowledge.doc.dao.DocruninfoDaoInter;
import com.wallellen.knowledge.doc.domain.Doc;
import com.wallellen.knowledge.doc.domain.DocMessage;
import com.wallellen.knowledge.doc.domain.DocRunInfo;
import com.wallellen.knowledge.doc.server.DocmessageManagerInter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.sql.SQLException;

/**
 * 留言板
 *
 * @author <a href="mailto:wallellen@hotmail.com">WALLE</a>
 */
@Service
public class DocmessageManagerImpl implements DocmessageManagerInter {
    @Resource
    private DocmessageDaoInter farmDocmessageDao;
    @Resource
    private DocruninfoDaoInter farmDocruninfoDao;
    @Resource
    private DocDaoInter farmDocDao;
    // private static final Logger log = Logger
    // .getLogger(FarmDocmessageManagerImpl.class);
    private final static Logger log = LoggerFactory.getLogger(DocmessageManagerImpl.class);

    @Transactional
    public DocMessage sendMessage(String readUserId, String text, String title, String note, String appId,
                                  LoginUser sendUser) {
        DocMessage message = new DocMessage();
        message.setCtime(TimeTool.getTimeDate14());
        message.setCuser(sendUser.getId());
        message.setCusername(sendUser.getName());
        message.setAppid(appId);
        message.setContent(text);
        message.setPcontent(note);
        message.setPstate("1");
        message.setReadstate("0");
        message.setReaduserid(readUserId);
        message.setTitle(title);
        return farmDocmessageDao.insertEntity(message);
    }

    @Transactional
    public DocMessage reSendMessage(String messageId, String text, LoginUser sendUser) {
        DocMessage obMes = farmDocmessageDao.getEntity(messageId);
        DocMessage message = new DocMessage();
        message.setCtime(TimeTool.getTimeDate14());
        message.setCuser(sendUser.getId());
        message.setCusername(sendUser.getName());
        message.setAppid(obMes.getAppid());
        message.setContent(text);
        message.setPcontent(obMes.getPcontent());
        message.setPstate("1");
        message.setReadstate("0");
        message.setReaduserid(obMes.getCuser());
        message.setTitle(obMes.getTitle());
        return farmDocmessageDao.insertEntity(message);
    }

    @Transactional
    public void deleteMessage(String entity, LoginUser user) {
        farmDocmessageDao.deleteEntity(farmDocmessageDao.getEntity(entity));
    }

    @Transactional
    public DocMessage getMessage(String id) {
        if (id == null) {
            return null;
        }
        return farmDocmessageDao.getEntity(id);
    }

    @Transactional
    public DocMessage readMessage(String id) {
        if (id == null) {
            return null;
        }
        DocMessage obMes = farmDocmessageDao.getEntity(id);
        obMes.setReadstate("1");
        farmDocmessageDao.editEntity(obMes);
        return obMes;
    }

    @Override
    public DataQuery createMessageQuery(DataQuery query) {
        DataQuery dbQuery = DataQuery.init(query, "farm_docmessage a left join alone_auth_user c on c.id=a.READUSERID ",
                "a.id as id,a.CTIME as CTIME,a.CUSERNAME as CUSERNAME,a.CUSER as CUSER,a.PSTATE as PSTATE,a.PCONTENT as PCONTENT,a.READUSERID as READUSERID,c.name as READUSERNAME,a.CONTENT as CONTENT,a.TITLE as TITLE,a.APPID as APPID,a.READSTATE as READSTATE");
        return dbQuery;
    }

    // ----------------------------------------------------------------------------------
    public DocmessageDaoInter getfarmDocmessageDao() {
        return farmDocmessageDao;
    }

    public void setfarmDocmessageDao(DocmessageDaoInter dao) {
        this.farmDocmessageDao = dao;
    }

    public DocruninfoDaoInter getFarmDocruninfoDao() {
        return farmDocruninfoDao;
    }

    public void setFarmDocruninfoDao(DocruninfoDaoInter farmDocruninfoDao) {
        this.farmDocruninfoDao = farmDocruninfoDao;
    }

    public DocDaoInter getFarmDocDao() {
        return farmDocDao;
    }

    public void setFarmDocDao(DocDaoInter farmDocDao) {
        this.farmDocDao = farmDocDao;
    }

    @Override
    public DocMessage sendMessage(String readUserId, String text, String title, String note, LoginUser sendUser) {
        return sendMessage(readUserId, text, title, note, null, sendUser);
    }

    @Override
    public int getNoReadMessageNum(LoginUser user) {
        return farmDocmessageDao.getNoReadMessageNum(user.getId());
    }

    @Override
    @Transactional
    public DocMessage sendAnswering(String content, String title, String mark, String appid, LoginUser sendUser) {
        DocMessage message = new DocMessage();
        message.setCtime(TimeTool.getTimeDate14());
        message.setCuser(sendUser.getId());
        message.setCusername(sendUser.getName());
        message.setAppid(appid);
        message.setContent(content);
        message.setPcontent(mark);
        message.setPstate("1");
        message.setReadstate("0");
        message.setTitle(title);
        message.setReaduserid("NONE");
        // 如果是文档就刷新文档的用量信息
        Doc doc = farmDocDao.getEntity(appid);
        if (doc != null) {
            DocRunInfo info = farmDocruninfoDao.getEntity(doc.getRuninfoid());
            int num = farmDocmessageDao.getAppMessageNum(appid);
            info.setAnsweringnum(num + 1);
            farmDocruninfoDao.editEntity(info);
        }
        return farmDocmessageDao.insertEntity(message);
    }

    @Override
    public DataResult getMessages(String docid, int num, int pagesize) {
        DataQuery dbQuery = DataQuery.init(new DataQuery(),
                "FARM_DOCMESSAGE A "
                        + "LEFT JOIN ALONE_AUTH_USER C ON C.ID=A.READUSERID "
                        + "LEFT JOIN ALONE_AUTH_USER D ON A.CUSER = D.ID",
                "A.ID AS ID,A.CTIME AS CTIME,A.CUSERNAME AS CUSERNAME,A.CUSER AS CUSER,"
                        + "A.PSTATE AS PSTATE,A.PCONTENT AS PCONTENT,A.READUSERID AS READUSERID,"
                        + "C.NAME AS READUSERNAME,A.CONTENT AS CONTENT,A.TITLE AS TITLE,A.APPID AS APPID,"
                        + "A.READSTATE AS READSTATE, D.IMGID AS IMGID");
        dbQuery.addRule(new DBRule("APPID", docid, "="));
        dbQuery.addSort(new DBSort("CTIME", "DESC"));
        dbQuery.setCurrentPage(num);
        dbQuery.setPagesize(pagesize);
        DataResult result = null;
        try {
            result = dbQuery.search();
        } catch (SQLException e) {
            log.error(e.toString());
            return DataResult.getInstance();
        }
        return result;
    }

}
